package marksys.free.com.marksys.ui.fragment.clean;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import java.util.Objects;

import javax.inject.Inject;

import dagger.Lazy;
import dagger.android.support.DaggerFragment;
import marksys.free.com.marksys.R;
import marksys.free.com.marksys.databinding.FragmentRecordCleanBinding;
import marksys.free.com.marksys.nettool.MyApi;
import marksys.free.com.marksys.nettool.common.Resource;
import marksys.free.com.marksys.nettool.common.Status;
import marksys.free.com.marksys.nettool.vo.Detail;
import marksys.free.com.marksys.nettool.vo.ScoreRecords;
import marksys.free.com.marksys.repo.HistoryRepo;
import marksys.free.com.marksys.ui.SettingActivity;
import marksys.free.com.marksys.ui.common.LinearLayoutColorDivider;
import marksys.free.com.marksys.ui.user.DetailActivity;
import marksys.free.com.marksys.utils.HttpErrorProcess;
import timber.log.Timber;

import static android.app.Activity.RESULT_OK;

public class RecordCleanFragment extends DaggerFragment {
    Detail detail;
    long recordId;
    FragmentRecordCleanBinding binding;
    @Inject
    HistoryRepo repo;
    @Inject
    Lazy<HttpErrorProcess> httpErrorProcess;
    RecordCleanViewModel viewModel;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_record_clean, container, false);
        viewModel = new RecordCleanViewModel(repo);
        binding.refreshLayout.setOnRefreshListener(viewModel::refresh);
        return binding.getRoot();
    }

    public static final int REQUEST_HISTORY_LIST = 0xaa;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        RecordCleanAdapter adapter = new RecordCleanAdapter();

        adapter.setItemClickListener((ScoreRecords data) -> {
            Timber.i("data %s", data);
            recordId = data.id;
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra(DetailActivity.RecordID, recordId);
            startActivityForResult(intent, 0xff);
        });

        adapter.setOnItemDeleteClickListener(data -> {
            recordId = data.id;
            new AlertDialog.Builder(Objects.requireNonNull(getActivity()))
                    .setTitle("提示")
                    .setMessage("是否删除该评分记录？")
                    .setPositiveButton("确定", (dialog, which) -> {
                        //该条评分记录清除
                        MyApi.delete(recordId).observe(this, apiResultResource -> {
                            assert null != apiResultResource;
                            if (apiResultResource.status == Status.SUCCESS) {
                                Toast.makeText(getActivity(), "撤销成功", Toast.LENGTH_SHORT).show();
                                viewModel.refresh();
                            }
                        });
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });

        adapter.setOnItemChangeClickListener(data -> {
            recordId = data.id;
            MyApi.detail(recordId).observe(this, (Resource<Detail> detailResource) -> {
                assert null != detailResource;
                detail = detailResource.data;
                assert detail != null;
                switch (detailResource.status) {
                    case LOADING:
                        break;
                    case SUCCESS:
                        Intent intent = new Intent(getActivity(), SettingActivity.class);
                        intent.putExtra(SettingActivity.KEY, 2);
                        intent.putExtra(SettingActivity.DETAIL, detail);
                        startActivityForResult(intent, 0xff);
                        break;
                    case ERROR:
                        httpErrorProcess.get().process(detailResource);
                        break;
                }
            });
        });

        adapter.setOnLoadMoreListener(viewModel::loadMore);
        binding.recyclerView.addItemDecoration(new LinearLayoutColorDivider(getActivity(), 0xfff8f8f8, 16, 1));
        binding.recyclerView.setAdapter(adapter);
        viewModel.hasMoreData.observe(this, adapter::hasMoreData);
        viewModel.cleandData.observe(this, newsResource -> {
            assert newsResource != null;
            switch (newsResource.status) {
                case LOADING:
                    if (!binding.refreshLayout.isRefreshing()) {
                        binding.refreshLayout.setRefreshing(true);
                    }
                    break;
                case ERROR:
                    httpErrorProcess.get().process(newsResource);
                    binding.refreshLayout.setRefreshing(false);
                    break;
                case SUCCESS:
                    adapter.submitList(newsResource.data);
                    binding.refreshLayout.setRefreshing(false);
                    break;
            }
        });
        viewModel.loadMoreStatus.observe(this, loadMore -> {
            assert loadMore != null;
            switch (loadMore.status) {
                case ERROR:
                    httpErrorProcess.get().process(loadMore);
                    break;
                case SUCCESS:
                    break;
                case LOADING:
                    break;
            }
        });
        viewModel.setQueryKey(null);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == REQUEST_HISTORY_LIST || requestCode == 0xff) && resultCode == RESULT_OK) {
            viewModel.refresh();
        }
    }

}

